package redis

import (
	"fmt"
	"time"

	"github.com/go-redis/redis/v8"

	"gitee.com/csingo/cLog"

	"gitee.com/csingo/cDB/drivers"
)

type Connector struct {
	connection string
	config     *Connection
	db         *redis.Client
}

func (i *Connector) GetConnection() string {
	return i.connection
}

func (i *Connector) GetDriver() drivers.DriverInterface {
	return i.config
}

func (i *Connector) GetDB() any {
	return i.db
}

func (i *Connector) Connect() error {
	if i.config == nil {
		return fmt.Errorf("redis client config is nil")
	}

	addr := fmt.Sprintf("%s:%d", i.config.Host, i.config.Port)
	pool := &ConnectionPool{}

	if i.config.Pool != nil {
		pool = i.config.Pool
	}

	if pool.MinIdleConns <= 0 {
		pool.MinIdleConns = 1
	}

	if pool.IdleTimeout <= 0 {
		pool.IdleTimeout = 10
	}

	if pool.Size <= 0 {
		pool.Size = 10
	}

	option := &redis.Options{
		Addr:         addr,
		Password:     i.config.Auth,
		DB:           int(i.config.DB),
		MaxRetries:   int(i.config.Retries),
		DialTimeout:  time.Duration(i.config.DialTimeout) * time.Second,
		ReadTimeout:  time.Duration(i.config.DialTimeout) * time.Second,
		WriteTimeout: time.Duration(i.config.DialTimeout) * time.Second,
		PoolSize:     int(pool.Size),
		MinIdleConns: int(pool.MinIdleConns),
		PoolTimeout:  time.Duration(pool.PoolTimeout) * time.Second,
		IdleTimeout:  time.Duration(pool.IdleTimeout) * time.Second,
	}

	i.db = redis.NewClient(option)

	cLog.WithContext(nil, map[string]any{
		"source":     "cDB.Connector.Connect",
		"connection": i.connection,
	}, []cLog.Option{
		cLog.IncludePaths{},
	}).Trace("创建 redis 连接客户端")

	return nil
}

func NewRedisConnector(connection string, config *Connection) (*Connector, error) {
	connector := &Connector{
		connection: connection,
		config:     config,
		db:         nil,
	}
	err := connector.Connect()

	return connector, err
}
